

const crypto = require('crypto')
const fs = require('fs')
const base64url = require('base64-url')




/**
 * BASE64URL(UTF8(JWE Protected Header)) || '.' ||
 * BASE64URL(JWE Encrypted Key) || '.' ||
 * BASE64URL(JWE Initialization Vector) || '.' ||
 * BASE64URL(JWE Ciphertext) || '.' ||
 * BASE64URL(JWE Authentication Tag)
 * 
 * @param {*} header 
 * @param {*} cek_enc 
 * @param {*} iv 
 * @param {*} ciphertext 
 * @param {*} tag 
 */
function verify(header,cek_enc,iv,ciphertext,tag){
    // 读取私钥文件
    let primaryKeyStr = fs.readFileSync("./rsa-prv.pem","utf8")
    const cek = crypto.privateDecrypt({key:primaryKeyStr,padding: crypto.constants.RSA_PKCS1_OAEP_PADDING},cek_enc)

    const decipher = crypto.createDecipheriv('aes-128-gcm', cek, iv, {
        authTagLength: 16
      })
      let headerBase64 = base64url.encode(JSON.stringify(header))
      decipher.setAAD(Buffer.from(headerBase64,"ascii"))

      decipher.setAuthTag(tag)
      const receivedPlaintext = decipher.update(ciphertext, 'utf8', 'utf8')
      try {
         decipher.final()
      } catch (err) {
        console.error('Authentication failed!')
        return
      }
      return receivedPlaintext
}

module.exports = {
    verify: verify
};
